package com.tvserials.notification;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.*;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
import com.tvserials.notification.adapters.TabsPagerAdapter;
import com.tvserials.notification.adapters.TvSerialsArrayAdapter;
import com.tvserials.notification.adapters.TvSerialsExpandableListAdapter;
import com.tvserials.notification.preferences.SharedPreferencesUtils;
import com.tvserials.notification.preferences.ShowCaseManager;
import com.tvserials.notification.dto.Serial;
import com.tvserials.notification.utils.VOUtils;
import com.espian.showcaseview.OnShowcaseEventListener;
import com.espian.showcaseview.ShowcaseView;
import com.tvserials.notification.vo.SourceType;

import java.util.*;
import java.util.List;

/**
 * Created by Alex on 26.03.2014.
 */
public class SignSerialsActivity extends FragmentActivity implements
        SearchView.OnQueryTextListener, ActionBar.TabListener {

    private static final String TAG = "SignSerialsActivity";
    private SearchView mSearchView;
    private ShowcaseView showcaseView;
    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    private MenuItem showOnlySelectedItem;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_serials);

        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();

        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Adding Tabs
        String[] stringArray = getResources().getStringArray(R.array.navigationTitles);
        List<SourceType> sourceTypes = SharedPreferencesUtils.getSelectedSourceTypes(getApplicationContext());
        for (SourceType sourceType : sourceTypes) {
            actionBar.addTab(actionBar.newTab().setText(stringArray[sourceType.ordinal()])
                    .setTabListener(this));
        }

        mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), sourceTypes);
        viewPager.setAdapter(mAdapter);

        viewPager.setOnPageChangeListener(new ViewPagerChangeListener());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.sign_menu, menu);
        showOnlySelectedItem = menu.findItem(R.id.showSelected);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        mSearchView = (SearchView) searchItem.getActionView();
        setupSearchView(searchItem);
        if (SharedPreferencesUtils.getSerialsList(getApplicationContext()).isEmpty()) {
            showcaseView = ShowCaseManager.showCaseAllSerials(this);
            if (showcaseView != null) {
                showcaseView.setOnShowcaseEventListener(new ShowcaseEventListener());
//                getCurrentListView().setAlpha(0.2f);
            }
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.btnSelectAll:
                Log.w(TAG, "select all");
                if (showcaseView != null) {
                    hideShowCase();
                }
                selectAll(true);
                return true;
            case R.id.btnClearAll:
                selectAll(false);
                return true;
            case R.id.btnAccept:
            case android.R.id.home:
                Log.w(TAG, "save serials");
                saveSerialsList();
                finish();
                return true;
            case R.id.showSelected:
                showOnlySelectedItem.setChecked(!showOnlySelectedItem.isChecked());
                TvSerialsExpandableListAdapter listAdapter = (TvSerialsExpandableListAdapter) getCurrentListView().getExpandableListAdapter();
                if (listAdapter != null) {
                    boolean checked = showOnlySelectedItem.isChecked();
                    listAdapter.setShowOnlySelected(checked);
                    if (checked) {
                        listAdapter.expandAllGroups();
                    } else {
                        listAdapter.collapseAllGroups();
                    }
                    listAdapter.notifyDataSetChanged();
                }
                return true;
            /*case R.id.sortAlpha:
                if (getCurrentListView() != null && getCurrentListView().getAdapter() != null) {
                    ListAdapter adapter = getCurrentListView().getAdapter();
                    List<Serial> items = ((TvSerialsArrayAdapter) adapter).getData();
                    sortSerials(new SortAlphabeticallyComparator(), items);
                    updateListAdapter(items);
                }
                return true;
            case R.id.sortSelected:
                if (ge;2tCurrentListView() != null && getCurrentListView().getAdapter() != null) {
                    ListAdapter adapter = getCurrentListView().getAdapter();
                    List<Serial> items = ((TvSerialsArrayAdapter) adapter).getData();
                    sortSerials(new SortSelectedComparator(), items);
                    updateListAdapter(items);
                }
                return true;*/
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Grab selected items from all tab views,
     * and save to preferences
     */
    private void saveSerialsList() {
        List<Serial> serials = new ArrayList<Serial>();
        List<Serial> serialsList = SharedPreferencesUtils.getSerialsList(getApplicationContext());
        for (int i = 0; i < mAdapter.getCount(); i++) {
            Fragment fragment = mAdapter.getItem(i);
            if (fragment != null && fragment.getView() != null) {
                ExpandableListView listView = (ExpandableListView) fragment.getView().findViewById(R.id.listView1);
                TvSerialsExpandableListAdapter arrayAdapter = (TvSerialsExpandableListAdapter) listView.getExpandableListAdapter();

                if (arrayAdapter != null) {
                    List<Serial> selectedItems = arrayAdapter.getSelectedItems();
                    serials.addAll(selectedItems);
                }
            } else {
                //add items from saved list if view wasn't updated
                SourceType sourceType = SourceType.getSourceTypeByPosition(i + 1);
                serials.addAll(VOUtils.getSerialsBySourceType(serialsList, sourceType));
            }
        }

        List<Serial> selectedItems = VOUtils.getSelectedItems(serials);
        SharedPreferencesUtils.saveSerialsList(getApplicationContext(), selectedItems);
    }

    private void updateListAdapter(List<Serial> listItems) {
        if (getCurrentListView() != null) {
            TvSerialsArrayAdapter adapter = new TvSerialsArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_multiple_choice, listItems);
            getCurrentListView().setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }

    private void sortSerials(Comparator<? super Serial> comparator, List<Serial> origData) {
        Collections.sort(origData, comparator);
        Log.w(TAG, "Sorted the data");
    }

    private void hideShowCase() {
        showcaseView.hide();
    }

    private void selectAll(boolean b) {
        TvSerialsExpandableListAdapter arrayAdapter = (TvSerialsExpandableListAdapter) getCurrentListView().getExpandableListAdapter();
        if (arrayAdapter != null) {
            for (int i = 0; i < arrayAdapter.getGroupCount(); i++) {
                for (int k = 0; k < arrayAdapter.getChildsCount(i); k++) {
                    Serial item = (Serial) arrayAdapter.getChild(i, k);
                    item.setSelected(b);
                }
            }
            arrayAdapter.notifyDataSetChanged();
        }
    }

    private void setupSearchView(MenuItem searchItem) {
        searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
                | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
        mSearchView.setOnQueryTextListener(this);
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    public boolean onQueryTextChange(String newText) {
        Log.w(TAG, "onQueryTextChange:" + newText);
        TvSerialsExpandableListAdapter adapter = (TvSerialsExpandableListAdapter) getCurrentListView().getExpandableListAdapter();
        if (adapter != null) {
            adapter.scrollToItem(newText);
        }
        return false;
    }

    /**
     * Return list view from currently selected Fragment
     *
     * @return list view component, null if failed to get
     */
    public ExpandableListView getCurrentListView() {
        View view = mAdapter.getCurrentFragment().getView();
        if (view != null) {
            View listView = view.findViewById(R.id.listView1);
            return (ExpandableListView) listView;
        }
        return null;
    }

    private class ShowcaseEventListener implements OnShowcaseEventListener {
        @Override
        public void onShowcaseViewHide(ShowcaseView showcaseView) {
        }

        @Override
        public void onShowcaseViewDidHide(ShowcaseView showcaseView) {
            hideShowCase();
        }

        @Override
        public void onShowcaseViewShow(ShowcaseView showcaseView) {
        }
    }

    private class SortSelectedComparator implements Comparator<Serial> {
        @Override
        public int compare(Serial lhs, Serial rhs) {
            return Boolean.valueOf(rhs.isSelected()).compareTo(lhs.isSelected());
        }
    }

    private static class SortAlphabeticallyComparator implements Comparator<Serial> {
        @Override
        public int compare(Serial lhs, Serial rhs) {
            return lhs.getShowName().compareTo(rhs.getShowName());
        }
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
    }

    private class ViewPagerChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);

            TvSerialsExpandableListAdapter expandableListAdapter = (TvSerialsExpandableListAdapter) getCurrentListView().getExpandableListAdapter();
            if (expandableListAdapter != null) {
                showOnlySelectedItem.setChecked(expandableListAdapter.isShowOnlySelected());
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }
}